<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require './application/controllers/pc_controller.php';

class Template extends PC_controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('Projectmodel','m_project');
		$this->load->model('Templatemodel','m_template');
		$this->load->model('Widgetmodel','m_widget');
		$this->load->model('Frameworkmodel','m_framework');
		$this->load->model('Codemodel','m_code');
	}

	public function index(){
		$data = parent::index();
		$data['attr'] = array(
			'project_list' => $this->m_project->outputProjectList4Js(),
		);
		$this->load->view('template',$data);
	}

	public function getTemplateList(){
		$assist['where'] = getFilter($this->input->post(),Templatemodel::$searchField);
		$assist['like'] = getFilter($this->input->post(),Templatemodel::$likeField);
		$assist['sort'] = getSort($this->input->post(),Templatemodel::$sortField);
		$assist['pagination'] = getPagination($this->input->post());
		$project_ids = $this->m_project->getActiveProjectIdList();
		list($list,$count) = $this->m_template->getTemplateListSection($project_ids,$assist);

		$users = extractColumn($list,'user_id');
		$users = $this->m_user->getUserById($users);
		$users = reindexArray($users,'user_id');
		foreach ($list as &$record) {
			$record['user_name'] = '';
			if(isset($users[$record['user_id']])) $record['user_name'] = $users[$record['user_id']]['user_name'];
			preg_match_all('/<widget>(.*?)<\/widget>/s', $record['template_struct'], $matches);
			$record['template_struct_plain'] = implode('<br>', $matches[1]);
		}

		$this->response->setSuccess();
		$this->response->setItems($list);
		$this->response->setTotalCount($count);
		$this->response->responseExit();
	}

	public function getTemplate(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$template = $this->m_template->getTemplate($info['template_id']);

		$this->response->setSuccess();
		$this->response->setAddon(array('template'=>$template));
		$this->response->responseExit();
	}

	public function createTemplate(){
		$this->validate->setRule('project_id','integer');
		$this->validate->setRule('project_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_name','string');
		$this->validate->setRule('template_name','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_title','string');
		$this->validate->setRule('template_title','notnull',false);
		if(!$this->validate->run($this->input->post())){
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		if(!$this->m_template->checkNameAvailable($info['template_name'],$info['project_id'])){
			
			$this->response->setDetail($this->lang->line('error_project_name_used'));
			$this->response->responseExit();
		}

		$info['user_id'] = $this->m_app->getCurrentUserId();
		
		$info['template_time_lastmodified'] = NOW;
		$this->m_template->createTemplate($info);

		$this->response->setSuccess();
		$this->response->setAddon(array('project_id'=>$info['project_id']));
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}

	public function editTemplateBasicInfo(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('project_id','integer');
		$this->validate->setRule('project_id','optional');
		$this->validate->setRule('project_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_name','string');
		$this->validate->setRule('template_name','optional');
		$this->validate->setRule('template_name','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_title','string');
		$this->validate->setRule('template_title','notnull',false);
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		if(!$this->m_template->checkNameAvailable($info['template_name'],$info['project_id'],$info['template_id'])){
			
			$this->response->setDetail($this->lang->line('error_project_name_used'));
			$this->response->responseExit();
		}

		$info['user_id'] = $this->m_app->getCurrentUserId();
		$info['template_time_lastmodified'] = NOW;
		$this->m_template->editTemplate($info['template_id'],$info);

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}

	public function editTemplate(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_time_lastmodified','string');
		$this->validate->setRule('template_time_lastmodified','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_css','string');
		$this->validate->setRule('template_css','optional');
		$this->validate->setRule('template_css','notnull',false);
		$this->validate->setRule('template_css','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_struct','string');
		$this->validate->setRule('template_struct','optional');
		$this->validate->setRule('template_struct','notnull',false);
		$this->validate->setRule('template_struct','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$template = $this->m_template->getTemplate($info['template_id']);
		if($template['template_time_lastmodified'] != $info['template_time_lastmodified']){
			
			$this->response->setDetail($this->lang->line('error_edited'));
			$this->response->responseExit();
		}
		$info['user_id'] = $this->m_app->getCurrentUserId();
		/*$widgets = array();
		$str = $info['template_struct'];
		do{
			$start = strpos($str,'<widget');
			$end = strpos($str,'</widget');
			if($start === false || $end === false) break;
			$widgets[] =  trim(substr($str,$start+8,$end-$start-8));
			$str = substr($str,$end+9);
		}while(true);
		$widget_arr = $this->m_widget->getWidgetListByName($widgets,$template['project_id']);
		$widget_arr = reindexArray($widget_arr,'widget_name');
		$w_arr = array();
		foreach($widgets as $wname){
			if(isset($widget_arr[$wname])){
				$w_arr[] = strval($widget_arr[$wname]['widget_id']);
			}
		}
		$info['template_widget'] = json_encode($w_arr);*/
		$info['template_time_lastmodified'] = NOW;
		$this->m_template->editTemplate($info['template_id'],$info);

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->setAddon(array('template_time_lastmodified'=>NOW));
		$this->response->responseExit();
	}

	public function deleteTemplate(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$this->m_template->deleteTemplate($info['template_id']);

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}

	public function getTemplateWidgetList(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$template = $this->m_template->getTemplate($info['template_id']);
		

		$list = $this->m_widget->getWidgetListByStruct($template['template_struct'],$template['project_id']);
		
		$count = count($list);

		$this->response->setSuccess();
		$this->response->setItems($list);
		$this->response->setTotalCount($count);
		$this->response->responseExit();
	}

	public function getProjectWidgetList(){
		$this->validate->setRule('project_id','integer');
		$this->validate->setRule('project_id','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();
		$assist['like'] = getFilter($this->input->post(),Widgetmodel::$likeField);
		$list = $this->m_widget->getWidgetBasicListByProject($info['project_id'],$assist);
		$count = count($list);

		$this->response->setSuccess();
		$this->response->setItems($list);
		$this->response->setTotalCount($count);
		$this->response->responseExit();
	}

	public function downloadTemplateCss($template_id){
		$template = $this->m_template->getTemplate($template_id);
		if(empty($template)) show_404();
		global $compression_replace;

		$data = $template['template_css'];
	
		$widget_list = $this->m_widget->getWidgetListByStruct($template['template_struct'],$template['project_id']);
		foreach ($widget_list as $widget) {
			$data .= $widget['widget_css'];
		}

		$data = str_replace($compression_replace,'',$data);
		$data = str_replace('/uploads/','<?php echo RESOURCE_URL ?>',$data);
		$data = '<style>'.$data.'</style>'."\n";
		$data .= "<?php /*\n";
		$data .= '---TEMPLATE:'.$template['template_name']."---\n";
		$data .= '---EXPORT TIME:'.NOW."---\n";
		$data .= $template['template_struct'].'*/';
		$this->load->helper('download');
		force_download($template['template_name'].'.php',$data);
	}

	public function cloneTemplate(){
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		$this->validate->setRule('template_name','string');
		$this->validate->setRule('template_name','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();

		$template = $this->m_template->getTemplate($info['template_id']);
		if(empty($template)){
			
			$this->response->setDetail($this->lang->line('error_parameter'));
			$this->response->responseExit();
		}

		if(!$this->m_template->checkNameAvailable($info['template_name'],$template['project_id'])){
			
			$this->response->setDetail($this->lang->line('error_project_name_used'));
			$this->response->responseExit();
		}
		
		unset($template['template_id']);
		$template['user_id'] = $this->m_app->getCurrentUserId();
		$template['template_name'] = $info['template_name'];
		$template['template_time_lastmodified'] = NOW;
		$this->m_template->createTemplate($template);

		$this->response->setSuccess();
		$this->response->setDetail($this->lang->line('success_update'));
		$this->response->responseExit();
	}

	public function downloadStaticPage($template_id){
		$template = $this->m_template->getTemplate($template_id);
		if(empty($template)) show_404();
		$project_id = $template['project_id'];
		$project = $this->m_project->getProject($project_id);
		if(empty($project)) show_404();

	

		$commonFile = validate($project['project_commonfile'])?json_decode($project['project_commonfile']):array();


		$this->load->library('zip');
		//$this->zip->add_data('assets/jscript.js',$project_js_content);
		//$this->zip->add_data('assets/style.css',$project_css_content);
		foreach($commonFile as $file){
			$path = COMMON_PATH.$file;
			if(file_exists($path)){
				$data = file_get_contents($path);
				$this->zip->add_data('assets/common/'.$file,$data);
			}
		}


		//
		$view = file_get_contents(base_url().'t/'.$template_id);
		$view = str_replace('/uploads/'.$project['project_code'].'/','assets/',$view);
		$view = str_replace('/favicion.ico','/assets/favicion.ico',$view);
		$view = str_replace(COMMON_URL,'assets/common/',$view);

		$this->zip->add_data($template['template_name'].'.html',$view);

		unset($view);



		$file_list = scandir(UPLOAD_PATH.$project['project_code']);
		foreach($file_list as $file){
			$path = UPLOAD_PATH.$project['project_code'].'/'.$file;
			
			if(file_exists($path)&& !is_dir($path)){
				$data = file_get_contents($path);
				$this->zip->add_data('assets/'.$file,$data);
			}
		}
		if(file_exists(UPLOAD_PATH.$project['project_code'].'/sprite.png')){
			$data = file_get_contents(UPLOAD_PATH.$project['project_code'].'/sprite.png');
			$this->zip->add_data('assets/sprite.png',$data);
		}

		$this->zip->download($template['template_name'].'.zip');
	}


	public function viewStaticTemplateCss() {
		$this->validate->setRule('template_id','integer');
		$this->validate->setRule('template_id','message',$this->lang->line('error_parameter'));
		if(!$this->validate->run($this->input->post())){
			
			$this->response->setDetail($this->validate->getMessage());
			$this->response->responseExit();
		}

		$info = $this->validate->getResult();

		$template = $this->m_template->getTemplate($info['template_id']);
		if(empty($template)){
			$this->response->setDetail($this->lang->line('error_parameter'));
			$this->response->responseExit();
		}
		$project = $this->m_project->getProject($template['project_id']);
		if(empty($project)){
			$this->response->setDetail($this->lang->line('error_parameter'));
			$this->response->responseExit();
		}

		global $compression_replace;
		$data = '';
	
		$widget_list = $this->m_widget->getWidgetListByStruct($template['template_struct'],$template['project_id']);
		foreach ($widget_list as $widget) {
			$data .= $widget['widget_css'];
		}
		$data .= $template['template_css'];

		$data = str_replace('/uploads/'.$project['project_code'].'/','assets/',$data);
		$data = str_replace($compression_replace,'',$data);

		$this->response->setSuccess();
		$this->response->setAddon(array(
			'css' => $data,
		));
		$this->response->responseExit();
	}
}
/* End of file template.php */
/* Location: ./application/controllers/template.php */
